function [x1, y1, x2, y2, select_flag] = guirbsel(h_fig, h_axes);

% GUIRBSEL - obtain coordinates from selected region
%
%    [X1, Y1, X2, Y2, FLAG] = GUIRBSEL(H_FIG, H_AXES) allows the user
%    to select a region on the image displayed on H_AXES.  The region
%    is selected graphically using the mouse.  The coordinates of the
%    region are returned in (X1, Y1) and (X2, Y2).  FLAG indicates
%    whether a valid region was selected (0 if invalid, 1 if valid).

% By:   S.C. Molitor (smolitor@med.unc.edu)
% Date: May 18, 2000

% check input parameters

if ((nargin < 2) | (nargin > 3))
   msgbox('Invalid number of arguments', 'GUIRBSEL Error', 'warn');
   return
elseif (~istype(h_fig, 'figure'))
   msgbox('H_FIG must be a valid figure handle', 'GUIRBSEL Error', 'warn');
   return
elseif (~istype(h_axes, 'axes'))
   msgbox('H_AXES must be a valid axes handle', 'GUIRBSEL Error', 'warn');
   return
elseif (nargin == 2)
   wait_flag = 'wait';
elseif (~ischar(wait_flag) | isempty(wait_flag))
   msgbox('WAIT must be a character string', 'GUIRBSEL Error', 'warn');
   return
end

% change pointer type
% change button down callbacks
% save old values

pointer_type = get(h_fig, 'Pointer');
set(h_fig, 'Pointer', 'crosshair');
button_down = get(h_fig, 'WindowButtonDownFcn');
set(h_fig, 'WindowButtonDownFcn', '');
button_up = get(h_fig, 'WindowButtonUpFcn');
set(h_fig, 'WindowButtonUpFcn', '');
h_child = [h_fig; h_axes; get(h_axes, 'Children')];
child_down = get(h_child, 'ButtonDownFcn');
set(h_child, 'ButtonDownFcn', '');

% obtain first point

k = waitforbuttonpress;
get_point = get(h_axes, 'CurrentPoint');
xp(1) = get_point(1, 1);
yp(1) = get_point(1, 2);

% if first is within axes limits, obtain second point
% display message to drag mouse to second point
% limit second point to be within axes ranges
% otherwise second point equals first point   

if (axesflag(h_axes, xp(1), yp(1)))
   finalrect = rbbox;
   get_point = get(h_axes, 'CurrentPoint');
   [xp(2), yp(2)] = axesflag(h_axes, get_point(1, 1), get_point(1, 2));
else
   xp(2) = xp(1);
   yp(2) = yp(1);
end

% order coordinates 

x1 = min(xp);
x2 = max(xp);
y1 = min(yp);
y2 = max(yp);

% determine selection flag based upon distinct coordinates

if ((x1 < x2) & (y1 < y2))
   select_flag = 1;
else
   select_flag = 0;
end

% reset pointer type
% reset button down callbacks

set(h_fig, 'Pointer', pointer_type);
set(h_fig, 'WindowButtonDownFcn', button_down);
set(h_fig, 'WindowButtonUpFcn', button_up);
for i = 1 : min(length(h_child), length(child_down))
   set(h_child(i), 'ButtonDownFcn', child_down{i});
end
return
